<template>
    <div class="pageClose">
        <div @click="router.replace({ path: '/order/orderTable' })">关闭</div>
    </div>
    <div class="page">
        <div class="pageBox">
            <div class="pageLeft">
                <div class="content">
                    <div class="orderNum">
                        <div>桌台：{{ rfData.roomName }}</div>
                        <span>订单号：{{ rfData.orderBatchCode }}</span>
                    </div>
                    <div class="moneyInfo">
                        <div class="moneyType">
                            <div>退款总额</div>
                            <span>{{ numJD(rfData.returnGoodsPrice) }}</span>
                        </div>
                        <div class="moneyType">
                            <div>已退金额</div>
                            <span>{{ numJD(beforeRefund) }}</span>
                        </div>
                        <div class="moneyType">
                            <div>还需退款</div>
                            <span>{{ numJD(moneyRemainder) }}</span>
                        </div>
                    </div>
                    <div class="methodTitle">
                        <div>请选择一种退款方式</div>
                        <div class="search-btn-box-pay">
                            <el-button @click="handlePay" class="search-btn-pay">网上支付查询</el-button>
                        </div>
                    </div>
                    <div class="refundMethod">
                        <div class="refundItem" v-for="(item, index) in refundType" :key="index">
                            <div class="itemIntro">
                                <img :src="item.logoUrl">
                                <div>{{ item.name }}退款<span>（最多可退<span v-if="item.name == '会员卡'">金额</span> ：￥{{ numJD(item.tempAmt) }}）</span></div>
                            </div>
                            <el-radio v-model="radio" :value="item.value" @click="refundChose(item)"></el-radio>
                        </div>
                    </div>
                </div>
                <div class="remark">
                    <div>退款备注：</div>
                    <textarea placeholder="选填"></textarea>
                </div>
            </div>
            <div class="pageRight">
                <div class="content">
                    <div class="Cashier">收银员：张三</div>
                    <div class="methodsTitle">
                        <div>退款方式</div>
                        <div>退款金额</div>
                    </div>
                    <div class="refundList">
                        <div class="refundItem" v-for="(item, index) in actRfList" :key="index">
                            <div class="itemLeft">{{ item.typeName }}退款</div>
                            <div class="itemRight">
                                <span>-￥{{ numJD(item.rfMoney) }}</span>
                                <img src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/pc/images/refund/del.png"
                                    @click="cancel(index)">
                            </div>
                        </div>
                    </div>
                    <div class="digitalBox">
                        <div class="digitalInput">
                            <div>退款金额：</div>
                            <input type="text" placeholder="请输入退款金额" v-model="refundMoney" @input="onInput(refundMoney)">
                        </div>
                        <div class="digitalMain">
                            <div @click="Num('1')">1</div>
                            <div @click="Num('2')">2</div>
                            <div @click="Num('3')">3</div>
                            <div @click="numDel()"><img
                                    src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/pc/images/orderDishes/del.png"></div>
                            <div @click="Num('4')">4</div>
                            <div @click="Num('5')">5</div>
                            <div @click="Num('6')">6</div>
                            <div @click="numClear()">删除</div>
                            <div @click="Num('7')">7</div>
                            <div @click="Num('8')">8</div>
                            <div @click="Num('9')">9</div>
                            <div>取消</div>
                            <div @click="Num('0')">0</div>
                            <div @click="Num('.')">·</div>
                            <div @click="subRfType()">确认</div>
                        </div>
                    </div>
                </div>

                <div class="refundBtn" @click="refundBtn()">退款</div>
            </div>
        </div>
    </div>
    <PayDialog ref="PayRef" v-if="PayVisible" :visible="PayVisible" :payItemCode="payItemCode" @emitCancel="emitPayCancel"
        @emitSubmit="emitPaySubmit" />
</template>

<script setup>
import ls from '@/lib/ls'
import Api from '@/api'
import { object } from 'superstruct'
import { getLocalIPv4 } from "@/utils/getip.js";
import PayDialog from '@/views/workbench/onorder/payDialog.vue'
const router = useRouter()
const route = useRoute()
const radio = ref('1')
const refundType = ref([])
const rfTypeItem = ref('')
const refundMoney = ref('')
const onInput = (money) => {
    if (Number(money) > rfTypeItem.value.tempAmt) {
        ElNotification({
            title: '提示',
            message: '超出总退款金额',
            type: 'warning',
        })
        if (rfTypeItem.value.tempAmt >= moneyRemainder.value) {
            refundMoney.value = moneyRemainder.value
        } else {
            refundMoney.value = numJD(rfTypeItem.value.tempAmt)
        }
        refundMoney.value = numJD(refundMoney.value)
        console.log(refundMoney.value, 'refundMoney.value')
    }else if (Number(money) > moneyRemainder.value) {
        ElNotification({
            title: '提示',
            message: '超出还需退款金额',
            type: 'warning',
        })
        if (rfTypeItem.value.tempAmt >= moneyRemainder.value) {
            refundMoney.value = numJD(moneyRemainder.value)
        } else {
            refundMoney.value = numJD(rfTypeItem.value.tempAmt)
        }
        refundMoney.value = numJD(refundMoney.value)
        console.log(refundMoney.value, 'refundMoney.value')
    }

}
const refundChose = (item) => {
    rfTypeItem.value = item
    refundMoney.value = ''
}
const actRfList = ref([])
const beforeRefund = ref(0)
const subRfType = () => {
    rfTypeItem.value.tempAmt = numJD(rfTypeItem.value.tempAmt)
    // console.log(rfTypeItem.value)
    console.log(actRfList.value)
    if (refundMoney.value && refundMoney.value > 0) {
        beforeRefund.value += numJD(Number(refundMoney.value))
        moneyRemainder.value = numJD(moneyRemainder.value - refundMoney.value)
        let check = false
        if (actRfList.value.length > 0) {
            actRfList.value.map(e => {
                if (e.itemCode == rfTypeItem.value.itemCode) {
                    check = true
                    e.rfMoney = Number(e.rfMoney) + Number(refundMoney.value)
                    e.rfMoney = e.rfMoney.toString()
                }
            })
            console.log(actRfList.value, 'actRfList.value')
        }
        if (check == false) {
            let temp = {
                typeName: rfTypeItem.value.name,
                rfMoney: refundMoney.value,
                itemCode: rfTypeItem.value.itemCode
            }
            actRfList.value.push(temp)
            console.log(actRfList.value, 'actRfList.value')
        }
        rfTypeItem.value.tempAmt -= numJD(refundMoney.value)
        refundMoney.value = ''
    }
}
const cancel = (index) => {
    console.log(actRfList.value[index])
    refundType.value.map(e => {
        if(e.itemCode == actRfList.value[index].itemCode){
            e.tempAmt += Number(actRfList.value[index].rfMoney)
        }
    })
    // return
    beforeRefund.value -= Number(actRfList.value[index].rfMoney)
    moneyRemainder.value += Number(actRfList.value[index].rfMoney)
    actRfList.value.splice(index, 1)
}

const Num = (count) => {
    refundMoney.value += count
    onInput(refundMoney.value)
}
const numDel = () => {
    refundMoney.value = refundMoney.value.slice(0, refundMoney.value.length - 1)
}
const numClear = () => {
    refundMoney.value = ''
}

// RoomConsumeList.value[typeIndex.value].storeDay = RoomConsumeList.value[typeIndex.value].storeDay.slice(0,RoomConsumeList.value[typeIndex.value].storeDay.length -1)

const rfData = ref(route.query)
console.log('rfData :>> ', rfData);
const moneyRemainder = ref(rfData.value.returnGoodsPrice)

//退款方式列表
const RefundStatistics = () => {
    let contentData = {
        consumeCode: ls.get('TABLE_INFO').consumeCode,
        payBatchCode: rfData.value.payBatchCode
    }
    Api.Common.PcObjProcess.Do({ "functionName": "GoodChangeRefundStatistics", contentData })
        .then(res => {
            console.log(res.typePayAmts)
            refundType.value = res.typePayAmts
            for (let i = 0; i < refundType.value.length; i++) {
                refundType.value[i].value = (i + 1).toString()
                refundType.value[i].tempAmt = refundType.value[i].amt
            }
            rfTypeItem.value = refundType.value[0]
            console.log(rfTypeItem.value)
        })
}
const reFlag = ref(false)
// 退款按钮
const refundBtn = async () => {
    console.log(moneyRemainder.value)
    // return
    if (moneyRemainder.value > 0) {
        ElNotification({
            title: '提示',
            message: '还需退款金额应为' + moneyRemainder.value,
            type: 'warning',
        })
        return
    }
    if(reFlag.value){
        ElNotification({
            title: '提示',
            message: '加载中，请稍等',
            type: 'warning',
        })
        return
    }
    reFlag.value = true
    if (rfData.value.todo == 'orderChange') {
        await orderChange()
    } else {
        // await returnDish()
    }
    let contentData = {
        "consumeCode": ls.get('TABLE_INFO').consumeCode,
        "roomCode": ls.get('TABLE_INFO').roomCode,
        "orderBatchCode": rfData.orderBatchCode,
        "payBatchCode": rfData.value.payBatchCode,
        "detail": [],
        "goodsItemCodeList":rfData.value.goodsItemCodeList
    }

    let newscontentData = ls.get('CONTENTDISH')
    newscontentData = {...newscontentData,ip:ip.value};
    contentData.returngoodsdetail =  newscontentData.detail;
    contentData.returnReason = newscontentData.returnReason || rfData.value.returnReason;
    contentData.ip=ip.value;

    let details = {}
    contentData.refunddetail = []
    refundType.value.map(e => {
        details = {
            payItemCode: e.itemCode,
            payType: e.code,
            refundFee: Number((e.amt - e.tempAmt).toFixed(2)),
            tradeNo: e.tradeNo,
            memberCode: e.memberCode
        }
        contentData.refunddetail.push(details)
    })

    console.log(contentData,'contentData')
    let obj = { functionName: "ReturnGoods", contentData }
    console.log(JSON.stringify(obj));
    
    // return
    Api.Common.PcObjProcess.Do({ functionName: "ReturnGoods", contentData })
        .then(res => {
            console.log(res)
            reFlag.value = false
            alert('退款成功')
            router.replace('/order/orderTable')
            ls.remove('CONTENTDISH')
        })
        if (rfData.value.todo != 'orderChange') {
             returnPrint(contentData.detail);
        }else{
            changePrint(contentData.detail);
        }
}
// 计算精度
const numJD = (num) => {
    let result = Number(num).toFixed(2);
    return parseFloat(result)
}
RefundStatistics()
// 退菜
// const returnDish = async() => {
//     let contentData = ls.get('CONTENTDISH')
//     contentData = {...contentData,ip:ip.value};
//     Api.Common.PcObjProcess.Do({ "functionName": "OpPayBatchReturnGoods", contentData })
//         .then(res => {
//             ElNotification({
//                 title: '提示',
//                 message:'退菜成功',
//                 type: 'success',
//             })
//         })
// }

//获取ip地址
const ip = ref("");
getLocalIPv4()
    .then((ipAddress) => {
        // 在这里处理获取到的 IP 地址
        ip.value = ipAddress;
        console.log("IP 地址:", ip.value);
    })
    .catch((error) => {
        console.error("发生错误:", error);
        // 在这里处理错误情况
    });

//退菜(退款小票)打印
const returnPrint = (payDetail) => {
    const goodsData = ls.get('CONTENTDISH')
    const contentData={...goodsData,...{payDetail:payDetail},ip:ip.value}
    console.log(contentData)
    Api.Common.PcObjProcess.Do({ "functionName": "RefundGoodPrint", contentData })
        .then(res => {
            console.log(res)
        })
}

//换菜(换菜退款小票)打印
const changePrint = (payDetail) => {
    let contentData = JSON.parse(router.currentRoute.value.query.contentData)
    contentData={...contentData,...{refundDetail:payDetail},ip:ip.value}
    console.log(contentData)
    Api.Common.PcObjProcess.Do({ "functionName": "ChangeGoodPrint", contentData })
        .then(res => {
            console.log(res)
        })
}

// 换菜
const orderChange = async() => {
    let contentData = JSON.parse(router.currentRoute.value.query.contentData)
    contentData={...contentData,ip:ip.value};
    Api.Common.PcObjProcess.Do({ functionName: "OpPayBatchChangeGoods", contentData })
        .then(res => {
            console.log('换菜res :>> ', res);
            ElNotification({
                title: '提示',
                message: '换菜成功',
                type: 'success',
            })
        })
}

// 点击网上支付查询
let PayVisible = ref(false)
const PayRef = ref()
const handlePay = (name) => {
    PayVisible.value = true
    //   nextTick(() => {
    //     PayRef.value.open(user.re)
    //   });
}
// 取消表格弹窗
const emitPayCancel = (params) => {
    console.log(params)
    PayVisible.value = false
}
// 提交表格弹窗
const emitPaySubmit = (params) => {
    console.log(params)
    PayVisible.value = false
}



</script>

<style scoped lang="scss">
* {
    color: #212121;
}

.pageClose {
    display: flex;
    justify-content: flex-end;
    background-color: #F2F2F2;
    box-sizing: border-box;
    padding: 0 100px;
    cursor: pointer;

    div {
        width: 120px;
        margin: 20px 0;
        font-size: 18px;
        background-color: #CCCCCC;
        padding: 20px 0;
        text-align: center;
        border-radius: 10px;
    }

}

.page {
    box-sizing: border-box;
    padding: 0 19%;
    padding-bottom: 30px;
    background-color: #F2F2F2;

    .pageBox {
        display: flex;
        justify-content: space-between;

        .pageLeft {
            width: 48.5%;

            .content {
                background-color: #fff;
                box-sizing: border-box;
                padding: 15px 20px;
                border-radius: 10px;
                height: 680px;

                .orderNum {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;

                    div {
                        font-size: 22px;
                        font-weight: bold;
                    }

                    span {
                        font-size: 16px;
                    }
                }

                .moneyInfo {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin: 20px 0;

                    .moneyType {
                        width: 31%;
                        background-color: #F2F2F2;
                        text-align: center;
                        border-radius: 10px;
                        padding: 10px 0;

                        div {
                            font-size: 16px;
                            margin-bottom: 10px;
                        }

                        span {
                            font-size: 20px;
                            font-weight: bold;
                        }
                    }

                    .moneyType:nth-child(2) {
                        span {
                            color: #0ACC6B;
                        }
                    }

                    .moneyType:nth-child(3) {
                        span {
                            color: #FF3333;
                        }
                    }
                }

                .methodTitle {
                    padding: 15px 0;
                    border-bottom: 1px solid #E6E6E6;
                    font-size: 18px;
                    display: flex;
                    justify-content: space-between;
                }

                .refundMethod {
                    .refundItem {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;

                        .itemIntro {
                            display: flex;
                            align-items: center;
                            padding: 20px 0;

                            img {
                                width: 30px;
                                height: auto;
                                margin-right: 16px;
                            }

                            div {
                                font-size: 16px;

                                span {
                                    font-size: 15px;
                                    color: #666666;
                                }
                            }
                        }

                        ::v-deep(.el-radio) {
                            margin-right: 15px;

                            .el-radio__inner {
                                width: 20px;
                                height: 20px;
                                border: 2px solid #666666;
                            }

                            .el-radio__input.is-checked .el-radio__inner:after {
                                transform: translate(-50%, -50%) scale(2);
                                background: #FF6B00;
                            }

                            .el-radio__input.is-checked .el-radio__inner {
                                background: #fff;
                                border: 2px solid #FF6B00;
                            }
                        }
                    }
                }
            }

            .remark {
                margin-top: 30px;

                div {
                    font-size: 16px;
                }

                textarea {
                    width: 100%;
                    height: 80px;
                    line-height: 1.5;
                    resize: none;
                    box-sizing: border-box;
                    padding: 15px 20px;
                    border-radius: 10px;
                    margin-top: 10px;
                    font-size: 16px;
                }
            }
        }

        .pageRight {
            width: 48.5%;

            .content {
                background-color: #fff;
                box-sizing: border-box;
                padding: 15px 0;
                border-radius: 10px;
                height: 730px;

                .Cashier {
                    font-size: 20px;
                    padding: 0 20px;
                }

                .methodsTitle {
                    display: flex;
                    align-content: center;
                    justify-content: space-between;
                    background-color: #E6E6E6;
                    padding: 14px 0;
                    margin: 15px 0;

                    div {
                        width: 40%;
                        box-sizing: border-box;
                        padding-left: 45px;
                        font-size: 16px;
                    }
                }

                .refundList {
                    height: 280px;

                    .refundItem {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        background-color: #F9F9F9;
                        margin: 20px;
                        border-radius: 10px;
                        box-sizing: border-box;
                        padding: 10px 25px;

                        .itemLeft {
                            font-size: 16px;
                        }

                        .itemRight {
                            display: flex;
                            align-items: center;

                            span {
                                font-size: 16px;
                                color: #FF3333;
                            }

                            img {
                                width: 30px;
                                height: auto;
                                margin-left: 35px;
                                cursor: pointer;
                            }
                        }
                    }
                }

                .digitalBox {
                    .digitalInput {
                        display: flex;
                        align-items: center;
                        margin: 0 25px;

                        div {
                            font-size: 16px;
                            width: 16%;
                        }

                        input {
                            background-color: #F9F9F9;
                            width: 84%;
                            box-sizing: border-box;
                            padding: 15px 20px;
                            border-radius: 10px;
                            font-size: 16px;
                        }
                    }

                    .digitalMain {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        flex-wrap: wrap;
                        width: 62%;
                        margin: auto;

                        div {
                            cursor: pointer;
                            width: 22%;
                            height: 50px;
                            margin-top: 15px;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            background-color: #E6E6E6;
                            font-size: 24px;
                            border-radius: 10px;

                            img {
                                width: 30px;
                                height: auto;
                            }
                        }

                        div:last-child {
                            width: 47.5%;
                            background-color: #FFD400;
                        }
                    }
                }

            }

            .refundBtn {
                background-color: #FF6A00;
                text-align: center;
                padding: 15px 0;
                color: #fff;
                font-size: 24px;
                border-radius: 10px;
                cursor: pointer;
                margin-top: 30px;
            }
        }
    }

}
</style>